﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.WebNemo.Business;

namespace blackhouse.WebNemo.Web {
	public partial class EditGroup : System.Web.UI.Page {

		#region Fields

		private int groupId;
		private IGroup group;

		#endregion

		#region Event Handlers

		protected void bntSave_Click(object sender, EventArgs e) {
			if (Page.IsValid)
				this.SaveGroup();
		}

		protected void cvCheckName_ServerValidate(object source, ServerValidateEventArgs args) {
			IGroupOperations go = Factory.Instance().GetGroupOperators();

			args.IsValid = go.CheckName(args.Value);
			if (args.IsValid) {
				ImpGroup g = new ImpGroup();
				g.SetName(args.Value);
				args.IsValid = go.CheckName(g.SystemName);
			}
		}

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.ReadParameters();
			this.Form.DefaultButton = this.bntSave.UniqueID;
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.SetInstance();
			if (!IsPostBack)
				this.PopulateControls();
		}

		#endregion

		#region Methods

		private void SaveGroup() {
			this.group.Name = this.txtName.Text;
			this.group.Identyficator = this.txtIdent.Text;
			this.group.Save();
			Response.Redirect("/EditGroup.aspx?groupId=" + this.group.Id);
		}

		private void ReadParameters() {
			string sGroupId = Request.QueryString["groupId"];
			if (!string.IsNullOrEmpty(sGroupId))
				Int32.TryParse(sGroupId, out groupId);
		}

		private void PopulateControls() {
			this.fldGroupId.Value = this.group.Id.ToString();
			this.txtName.Text = this.group.Name;
			this.txtIdent.Text = this.group.Identyficator;

			this.cvCheckName.Enabled = this.group.Id == 0;

			txtName.Focus();
		}

		private void SetInstance() {
			if (groupId > 0)
				this.group = Factory.Instance().GetGroup(this.groupId);
			else
				this.group = Factory.Instance().CreateGroup();
		}

		#endregion

	}
}